global !p
def env(name):
    [x,y] = vim.eval("vimtex#env#is_inside('" + name + "')") 
    return x != '0' and x != '0'
def math():
	res = (vim.eval('vimtex#syntax#in_mathzone()') == '1')
	return res
def comment():
	return vim.eval('vimtex#syntax#in_comment()') == '1'
def env(name):
	[x,y] = vim.eval("vimtex#env#is_inside('" + name + "')")
	return x != '0' and y != '0'
def python():
	try:
		pythontex_envs = ['pycode','pysub','pyverbatim','pyblock','pyconsole','pythontexcustomcode']
		name_env = vim.eval("vimtex#env#get_surrounding('normal')")[0]['name']
		return name_env in pythontex_envs
	except:
		try:
			pythontex_cmds = ['py','pyc','pys','pyb','pyv','pycon','pythontexcustomc']
			name_cmd = vim.eval("vimtex#cmd#get_current()")['name'][1:]
			return name_cmd in pythontex_cmds
		except:
			return False
def R():
	try:
		pythontex_envs = ['Rcode','Rsub','Rverbatim','Rblock','Rconsole']
		name_env = vim.eval("vimtex#env#get_surrounding('normal')")[0]['name']
		return name_env in pythontex_envs
	except:
		try:
			pythontex_cmds = ['R','Rc','Rs','Rb','Rv','Rcon']
			name_cmd = vim.eval("vimtex#cmd#get_current()")['name'][1:]
			return name_cmd in pythontex_cmds
		except:
			return False
def create_matrix_placeholders(snip):
	# Create anonymous snippet body
	anon_snippet_body = ""
	# Get start and end line number of expanded snippet
	start = snip.snippet_start[0]
	end = snip.snippet_end[0]
  # Append current line into anonymous snippet
	for i in range(start, end + 1):
		anon_snippet_body += snip.buffer[i]
		anon_snippet_body += "" if i == end else "\n"
	# Delete expanded snippet line till second to last line
	for i in range(start, end):
		del snip.buffer[start]
	# Empty last expanded snippet line while preserving the line
	snip.buffer[start] = ''
	# Expand anonymous snippet
	snip.expand_anon(anon_snippet_body)
def create_matrix(rows,cols, sep, start, end):
	res = ""
	# placeholder = 1
	placeholder = '<<>>' 
	for _ in range(0, int(rows)):
		res += start + f"{placeholder} "
		# placeholder += 1
		for _ in range(0, int(cols) - 1):
			res += sep + f" {placeholder} "
			# placeholder += 1
		res += end
	return res[:-1]
endglobal

priority 100

snippet table "Table environment" b
\begin{table}[${1:htpb}]
	\centering
	\caption{${2:caption}}
	\label{tab:${3:label}}
	\begin{tabular}{${5:c}}
	$0${5/((?<=.)c|l|r)|./(?1: & )/g}
	\end{tabular}
\end{table}
endsnippet

snippet fig "Figure environment" b
\begin{figure}[${1:htpb}]
	\centering
	${2:\includegraphics[width=0.8\textwidth]{$3}}
	\caption{${4:$3}}
	\label{fig:${5:${3/\W+/-/g}}}
\end{figure}
endsnippet
snippet graph "includegraphics" bA
\begin{center}
\includegraphics[width=$0\textwidth]{<<>>}
\end{center}
endsnippet

snippet enum "Enumerate" bA
\begin{enumerate}
	\item $0
\end{enumerate}
endsnippet

snippet item "Itemize" bA
\begin{itemize}
	\item $0
\end{itemize}
endsnippet

snippet desc "Description" b
\begin{description}
	\item[$1] $0
\end{description}
endsnippet

snippet plot "Plot" w
\begin{figure}[$1]
	\centering
	\begin{tikzpicture}
		\begin{axis}[
			xmin= ${2:-10}, xmax= ${3:10},
			ymin= ${4:-10}, ymax = ${5:10},
			axis lines = middle,
		]
			\addplot[domain=$2:$3, samples=${6:100}]{$7};
		\end{axis}
	\end{tikzpicture}
	\caption{$8}
	\label{${9:$8}}
\end{figure}
endsnippet

snippet node "Tikz node" w
\node[$5] (${1/[^0-9a-zA-Z]//g}${2}) ${3:at (${4:0,0}) }{$${1}$};
$0
endsnippet

# =====================
# custom snippets begin
# =====================

priority 20

snippet ,` "\begin{minted} / \end{minted}" bA
\\begin{minted}{$1}
$0
\\end{minted}
endsnippet

snippet "[,，]m" "\item" bAr
\item $1
endsnippet

snippet "[,，]1" "\part{}" bAr
\\part{$1}
endsnippet

snippet "[,，]2" "\chapter{}" bAr
\\chapter{$1}
endsnippet

snippet "[,，]3" "section{}" bAr
\\section{$1}
endsnippet

snippet "[,，]4" "\subsection{}" bAr
\\subsection{$1}
endsnippet

snippet "[,，]5" "\subsubsection{}" bAr
\\subsubsection{$1}
endsnippet

snippet "[,，]6" "\paragraph{}" bAr
\\paragraph{$1}
endsnippet

snippet "[,，]7" "\subparagraph{}" bAr
\\subparagraph{$1}
endsnippet

snippet ,v "\mintinline{}{} (needs `\usepackage{minted}`)" bwA
\\mintinline{${1:<<>>}}{${2:<<>>}}$0
endsnippet

snippet ,c "\verb``" bwA
\\verb\`$1\`$0
endsnippet

snippet ,d "``''" bwA
\`\`$1''$0
endsnippet

snippet ,s "`'" bwA
\`$1'$0
endsnippet

snippet "[,，]a" "\textbf{}" bwAr
\\textbf{${1:${VISUAL}}}$0
endsnippet

snippet ,b "begin{} / end{}" bA
\\begin{$1}
<<>>
\\end{$1}
endsnippet

snippet ,i "\textit{}" bwA
\\textit{${1:${VISUAL}}}$0
endsnippet

snippet "[,，]u" "\uline{} (\usepackage[normalem]{ulem})" bwAr
\\uline{${1:${VISUAL}}}$0
endsnippet

snippet "[,，]n" "\emph{}" bwAr
\\emph{${1:${VISUAL}}}$0
endsnippet

snippet "[,，]l" "\href{}{}" bwAr
\\href{$0}{<<>>}<<>>
endsnippet

snippet "[,，]f" "\footnote{}" bwAr
\\footnote{${1:${VISUAL}}}$0
endsnippet

snippet ,t "\citet{} (\usepackage{natbib})" bwA
\\citet{${1:${VISUAL}}}$0
endsnippet

snippet ,p "\citep{} (\usepackage{natbib})" bwA
\\citep{${1:${VISUAL}}}$0
endsnippet

snippet "(^|[^a-zA-Z0-9}]),," "\command" irA
`!p snip.rv = match.group(1)`\\$0
endsnippet

snippet "(\\[^{\s]+),," "\command{...}" rA
`!p snip.rv = match.group(1)`{$0}<<>>
endsnippet

snippet "(\\[^{\s]+)(\{[^}]+\}),," "\command[...]{...}" rA
`!p snip.rv = match.group(1)`[$1]`!p snip.rv = match.group(2)`$0
endsnippet

snippet "be(gin)?( (\S+))?" "begin{} / end{}" br
\begin{${1:`!p
snip.rv = match.group(3) if match.group(2) is not None else "something"`}}
	${2:${VISUAL}}
\end{$0}
endsnippet

# ====================
# custom snippets end
# ====================

priority 200
context "python()"
snippet p "print something"
print(${1:${VISUAL}})
endsnippet

context "python()"
snippet frs "read file as string"
with open(${1:filename}, 'r', encoding="utf-8") as f:
	${2:content} = f.read()
endsnippet

context "python()"
snippet frl "read file as list"
with open(${1:filename}, 'r', encoding="utf-8") as f:
	${2:lines} = ${3:[}line.strip() for line in f.readlines() if line.strip()${4:]}
endsnippet

context "python()"
snippet fw "override file"
with open(${1:filename}, '${2:w}', encoding="utf-8") as f:
	f.write(${3:content})
endsnippet

context "python()"
snippet c2t "call csv2table()" b
\\begin\{pycode}
import pandas as pd
fn = "${1:<<>>}"
args = \{
	"position": "htbp",
	"position_float": "centering",
	"hrules": True,
	"caption": "${2:<<>>}",
	"label": "tab:${3:<<>>}",
}
table = csv2table(fn, args)
print(table)
\\end\{pycode}
endsnippet

# custom snippets for math begin
snippet nn "equation" bA
\\begin{equation}
$0
\\end{equation}
endsnippet

snippet 8nn "equation without tag" bA
\\begin{equation*}
$0
\\end{equation*}
endsnippet
# snippet eq8 "equation without tag" b
# \\[
# $1
# \\]
# endsnippet

snippet $$ "inline math" iA
$ $1 $`!p
if t[2] and t[2][0] not in [',', '.', '?', '-', ' ', '，', '、', '；', '。']:
	snip.rv = ' '
else:
	snip.rv = ''
`${2:<<>>}
endsnippet

snippet ￥￥ "inline math" iA
$ $1 $`!p
if t[2] and t[2][0] not in [',', '.', '?', '-', ' ', '，', '、', '；', '。']:
	snip.rv = ' '
else:
	snip.rv = ''
`${2:<<>>}
endsnippet

snippet "(^|[^a-zA-Z0-9])mm" "inline math" irA
`!p snip.rv=match.group(1)`$ $1 $`!p
if t[2] and t[2][0] not in [',', '.', '?', '-', ' ', '，', '、', '；', '。']:
    snip.rv = ' '
else:
    snip.rv = ''
`${2:<<>>}
endsnippet

context "math()"
snippet ,f "=" wA
= $0
endsnippet

context "math()"
snippet "(t|d)?//" "fraction" wAr
\\`!p snip.rv=match.group(1) if match.group(1) else ''`frac{$1}{<<>>}<<>>
endsnippet

context "math()"
snippet '((\d+)|(\d*)(\\)?([A-Za-z]+)((\^|_)(\{\d+\}|\d))*)/' "Fraction" wrA
\\frac{`!p snip.rv = match.group(1)`}{<<>>}<<>>
endsnippet

context "math()"
snippet rt "\sqrt{}" wA
\\sqrt{$0}<<>>
endsnippet

context "math()"
snippet lrp "\left( \right)" iA
\\left($0\\right)<<>>
endsnippet
context "math()"
snippet lrb "\left[ \right]" iA
\\left[$0\\right]<<>>
endsnippet
context "math()"
snippet lrc "\left{ \right}" iA
\\left\\{$0\\right\\}<<>>
endsnippet
context "math()"
snippet lra "\left< \right>" iA
\\left<$0\\right><<>>
endsnippet
context "math()"
snippet lr| "\left| \right|" iA
\\left|$0\\right|<<>>
endsnippet
context "math()"
snippet tt "\text{}" wA
\\text{$0}<<>>
endsnippet
context "math()"
snippet ooo "\infty" iA
\\infty
endsnippet
context "math()"
snippet int "\int_{}^{}" w
\\int_{$0}^{<<>>}<<>>
endsnippet
context "math()"
snippet lim "\lim_{}" w
\\lim_{$0} \to <<>>}<<>>
endsnippet
context "math()"
snippet sum "sum_{}^{}" w
\\sum_{$0}^{<<>>}<<>>
endsnippet
context "math()"
snippet part "偏导" wA
\\frac{\\partial $0}{\\partial <<>>}<<>>
endsnippet
context "math()"
snippet diff "微分" wA
\\frac{\\mathrm{d}$0}{\\mathrm{d}<<>>}
endsnippet

context "math()"
snippet "(^|[^-])->" "\rightarrow" rA
\\xrightarrow $0
endsnippet
context "math()"
snippet "(^|[^-])-<" "\leftarrow" rA
\\xleftarrow $0
endsnippet
context "math()"
snippet --> "\longrightarrow" iA
\\longrightarrow $0
endsnippet
context "math()"
snippet --< "\longleftarrow" iA
\\longleftarrow $0
endsnippet
context "math()"
snippet ==> "\Longrightarrow" iA
\\Longrightarrow $0
endsnippet
context "math()"
snippet "(^|[^=])=>" "\Rightarrow" rA
\\Rightarrow $0
endsnippet
context "math()"
snippet ==< "\Longleftarrow" iA
\\Longleftarrow $0
endsnippet
context "math()"
snippet (^|[^=])=< "\Leftarrow" rA
\\Leftarrow $0
endsnippet
context "math()"
snippet <= "\le" iA
\\le $0
endsnippet
context "math()"
snippet >= "\ge" iA
\\ge $0
endsnippet

context "math()"
snippet != "\ne" iA
\\ne $0
endsnippet

context "math()"
snippet '([A-Za-z])(\d)' "auto subscript" wrA
`!p snip.rv = match.group(1)`_`!p snip.rv = match.group(2)`
endsnippet

context "math()"
snippet '([A-Za-z])_(\d\d)' "auto subscript2" wrA
`!p snip.rv = match.group(1)`_{`!p snip.rv = match.group(2)`}
endsnippet

# context "math()"
# snippet jw "superscript" iA
# ^{$0}<<>>
# endsnippet
# context "math()"
# snippet js "subscript" iA
# _{$0}<<>>
# endsnippet
# context "math()"
# snippet ja "上下标" iA
# _{$0}^{<<>>}<<>>
# endsnippet
context "math()"
snippet .. "superscript" iA
^{$0}<<>>
endsnippet
context "math()"
snippet ,, "subscript" iA
_{$0}<<>>
endsnippet
context "math()"
snippet ,. "suber- and sub-script" iA
_{$0}^{<<>>}<<>>
endsnippet

context "math()"
snippet pii "\pi" iA
\\pi$0
endsnippet
context "math()"
snippet ",d" "\delta" wA
\\delta$0
endsnippet
context "math()"
snippet ",D" "\Delta" wA
\\Delta$0
endsnippet

context "R()"
snippet ,f "=" wA
<- $0
endsnippet

priority 10
context "math()"
snippet "bar" "bar" riA
\overline{$0}<<>>
endsnippet

priority 100
context "math()"
snippet "([a-zA-Z])bar" "bar" riA
\overline{`!p snip.rv=match.group(1)`}
endsnippet

priority 10
context "math()"
snippet "hat" "hat" riA
\hat{$0}<<>>
endsnippet

priority 100
context "math()"
snippet "([a-zA-Z])hat" "hat" riA
\hat{`!p snip.rv=match.group(1)`}
endsnippet

context "math()"
snippet "(\\?\w+)(,\.|\.,)" "Vector postfix" riA
\vec{`!p snip.rv=match.group(1)`}
endsnippet

context "math()"
snippet ` "+" iA
+$0
endsnippet

context "math()"
snippet ee "e" iA
\mathrm{e}$0
endsnippet

context "math()"
snippet EE "geq" iA
\exists$0
endsnippet

context "math()"
snippet AA "forall" iA
\forall$0
endsnippet

context "math()"
snippet xnn "xn" iA
x_{n}$0
endsnippet

context "math()"
snippet ynn "yn" iA
y_{n}$0
endsnippet

context "math()"
snippet xii "xi" iA
x_{i}$0
endsnippet

context "math()"
snippet yii "yi" iA
y_{i}$0
endsnippet

context "math()"
snippet xjj "xj" iA
x_{j}$0
endsnippet

context "math()"
snippet yjj "yj" iA
y_{j}$0
endsnippet

context "math()"
snippet xp1 "x" iA
x_{n+1}$0
endsnippet

context "math()"
snippet xmm "x" iA
x_{m}$0
endsnippet

snippet R0+ "R0+" iA
\\R_0^+$0
endsnippet

context "math()"
snippet xx "cross" iA
\times$0
endsnippet

priority 100
context "math()"
snippet ** "cdot" iA
\cdot$0
endsnippet

context "math()"
snippet norm "norm" iA
\|$0\|<<>>
endsnippet

context "math()"
snippet >> ">>" iA
\gg $0
endsnippet

context "math()"
snippet << "<<" iA
\ll $0
endsnippet

context "math()"
snippet ~~ "~" iA
\sim $0
endsnippet

snippet notin "not in " iA
\not\in $0
endsnippet

context "math()"
snippet inn "in " iA
\in $0
endsnippet

context "math()"
snippet OO "emptyset" iA
\O $0
endsnippet

context "math()"
snippet RR "real" iA
\R $0
endsnippet

context "math()"
snippet QQ "Q" iA
\Q $0
endsnippet

context "math()"
snippet ZZ "Z" iA
\Z $0
endsnippet

context "math()"
snippet cvec "column vector" iA
\begin{pmatrix} ${1:x}_${2:1}\\\\ \vdots\\\\ $1_${3:n} \end{pmatrix}
endsnippet

context "math()"
snippet "(p|b|v|V)mat" "\begin{pmatrix} / \end{pmatrix}" wrA
\\begin{`!p snip.rv=match.group(1)`matrix} 
$0
\\end{`!p snip.rv=match.group(1)`matrix}<<>>
endsnippet

priority 1000
context "math()"
snippet '^.*\)/' "() Fraction" wrA
`!p
stripped = match.string[:-1]
depth = 0
i = len(stripped) - 1
while True:
	if stripped[i] == ')': depth += 1
	if stripped[i] == '(': depth -= 1
	if depth == 0: break;
	i -= 1
snip.rv = stripped[0:i] + "\\frac{" + stripped[i+1:-1] + "}"
`{$0}<<>>
endsnippet

context "math()"
post_jump "create_matrix_placeholders(snip)"
snippet 'arr,(\d+),(\d+)' "LaTeX array" br
\begin{array}{`!p
orient = ""
for _ in range(0, int(match.group(1))): orient += "l"
snip.rv = orient`}
`!p
snip.rv = create_matrix(match.group(1), match.group(2), "&", "\t", "\\\\\n")
`<<>>
\end{array}
endsnippet

context "math()"
post_jump "create_matrix_placeholders(snip)"
snippet '(\d+),(\d+)' "LaTeX array" br
`!p
snip.rv = create_matrix(match.group(1), match.group(2), "&", "\t", "\\\\\n")
`<<>>
endsnippet

# custom snippets for math end

# custom snippets for tikz begin
# context "env(tikzpicture)"
# snippet ,v "\Vertex" wA
# \\Vertex[IdAsLabel,Math,x=${2:0},y=${3:0},fontsize=\\${4:normalsize},fontcolor=${5:black},color=${6:white},size=${7:.6cm}]{${1:name}} ${0:<<>>}
# endsnippet
# context "env(tikzpicture)"
# snippet ,e "\Edge" wA
# \\Edge[Direct=${:true},label=${:label},fontsize=\\${:normalsize},fontcolor=${:black},lw=${:1}pt,color=${:black},bend=${:0}](${1:origin})(${2:destination})
# endsnippet
# custom snippets for tikz end
